package com.jianbing.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jianbing.entity.Result;
import com.jianbing.util.Constants;
import com.jianbing.util.IPUtil;

import net.sf.json.JSONObject;

public class CommInterceptor implements HandlerInterceptor {

	private Logger logger = Logger.getLogger(CommInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		if (IPUtil.checkIp(arg0)) {
			return true;
		}
		arg1.setContentType(Constants.jsonContentType);
		PrintWriter responseOut = arg1.getWriter();
		JSONObject returnJson = new JSONObject();
		returnJson.put("code", 199);
		returnJson.put("msg", "IP非法");
		responseOut.write(returnJson.toString());
		logger.info("IP非法---【" + IPUtil.getIpAddr(arg0) + "】");
		return false;
	}
}
